package com.changgou.file.controller;

import com.changgou.common.pojo.Result;
import com.changgou.common.pojo.StatusCode;
import com.changgou.file.util.FastDFSClient;
import com.changgou.file.util.FastDFSFile;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RequestMapping("/file")
@RestController
public class FileController {

    @PostMapping("uploadFile")
    public Result uploadFile(MultipartFile file){

        String originalFilename = null;
        try {
            if (file == null){
                throw new RuntimeException("文件不存在");
            }

            //文件名
            originalFilename = file.getOriginalFilename();
            if (StringUtils.isEmpty(originalFilename)){
                throw new RuntimeException("文件不存在");
            }
            //文件扩展名
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            //文件内容
            byte[] content = file.getBytes();

            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, content, extName);

            String[] uploadResult = FastDFSClient.upload(fastDFSFile);

            String url = FastDFSClient.getTrackerUrl() + uploadResult[0] + "/" + uploadResult[1];
            return new Result(true,StatusCode.OK,"文件上传成功",url);

        } catch (IOException e) {
            e.printStackTrace();
        }



        return new Result(false, StatusCode.ERROR,"文件上传失败");
    }

}
